package com.bit.net;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 响应报文编码
 *
 * @since 2018/10/10
 */
@Slf4j
public class ResponseEncoder extends MessageToByteEncoder<Response> {

    private EachModulModelMessages modelMessages;

    public ResponseEncoder(EachModulModelMessages modelMessages) {
        this.modelMessages = modelMessages;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Response msg, ByteBuf out) throws Exception {
        String jsonString = JSON.toJSONString(msg);

        log.debug("Game response json string:{}", jsonString);

        byte[] messageBody = jsonString.getBytes(CharsetUtil.UTF_8);

        out.writeBytes(Messages.MAGIC_NUMBER);
        out.writeByte(Messages.DEFAULT_VERSION);
        out.writeShort(messageBody.length + Messages.PKG_HEAD_SIZE);
        out.writeByte(modelMessages.getTargetCode(msg.getClass()));
        out.writeBytes(Messages.RESERVED);
        out.writeBytes(messageBody);
    }
}
